<template>
  <Card>
    <Row style="margin-left:10px;" class="titleline">
      <div class="detail-title">基本信息</div>
      <div class="line1"></div>
    </Row>
    <!-- 基本信息 -->
    <Row style="margin-top:20px; margin-left:140px;">
      <Form ref="addForm" :model="addForm" :rules="ruleValidate">
        <Row>
          <i-col
            span="3"
            style="text-align:right; margin-right:10px; height:32px; line-height:32px;"
          >
            <span style="color:red;">*</span>
            <span>俱乐部名称:</span>
          </i-col>
          <i-col span="12">
            <FormItem prop="clubname">
              <Input type="text" v-model="addForm.clubname" placeholder="俱乐部名称" clearable />
            </FormItem>
          </i-col>
        </Row>
        <Row>
          <i-col
            span="3"
            style="text-align:right; margin-right:10px; height:32px; line-height:32px;"
          >
            <div v-for="(item, index) in addForm.rewards" :key="index" style="margin-bottom:24px;">
              <span style="color:red;">*</span>
              <span>俱乐部奖励{{item.index}}:</span>
            </div>
          </i-col>
          <i-col span="12">
            <FormItem
              v-for="(item, index) in addForm.rewards"
              :key="index"
              :prop="'rewards.' + index + '.value'"
              :rules="{required: true, message: '俱乐部奖励 ' + item.index +' 不能为空', trigger: 'change'}"
            >
              <div>
                <i-input type="text" v-model="item.value"></i-input>
              </div>
              <div class="form-tip-1">
                <Icon
                  type="ios-add-circle-outline"
                  size="24"
                  v-if="item.index==addForm.rewards.length"
                  @click="handleAdd"
                />
                <Icon
                  type="ios-remove-circle-outline"
                  size="24"
                  v-if="item.index!==1&&item.index==addForm.rewards.length"
                  @click="handleRemove(index)"
                />
              </div>
            </FormItem>
          </i-col>
        </Row>
        <Row>
          <i-col
            span="3"
            style="text-align:right; margin-right:10px; height:32px; line-height:32px;"
          >
            <span style="color:red;">*</span>
            <span>俱乐部等级:</span>
          </i-col>
          <i-col span="14">
            <FormItem prop="level">
              <Rate :count="10" v-model="addForm.level" @on-change="rateChange" />
            </FormItem>
          </i-col>
        </Row>
        <Row>
          <i-col
            span="3"
            style="text-align:right; margin-right:10px; height:32px; line-height:32px;"
          >
            <span style="color:red;">*</span>
            <span>上传照片:</span>
          </i-col>
          <i-col span="16">
            <FormItem prop="imgFile">
              <div class="demo-upload-list">
                <template v-if="addForm.imgFile.name != ''">
                  <img :src="imgUrl" />
                  <div class="demo-upload-list-cover">
                    <!-- <Icon type="ios-eye-outline" @click.native="handleView(addForm.imgFile.name)"></Icon> -->
                    <Icon type="ios-trash-outline" @click.native="delectFile(addForm.imgFile)"></Icon>
                  </div>
                </template>
                <template v-else>
                  <div style="border: 1px dashed #dcdee2;">请选择俱乐部图片！</div>
                </template>
              </div>
              <Uploadv
                type="drag"
                ref="upload"
                :format="['jpg','jpeg','png']"
                :before-upload="handleUpload"
                :show-upload-list="false"
                :on-success="uploadSuccess"
                :on-error="uploadFail"
                :action="action"
                :headers="{
                  Authorization:this.tocken
                }"
                name="multipartFile"
                :data="dataObj"
                style="display:inline-block;width:88px;"
              >
                <div style="width:88px;height:28px;line-height:28px; border:1px solid #ccc;">
                  <!-- <Icon type="ios-camera" size="20"></Icon> -->
                  选择图片
                </div>
              </Uploadv>
            </FormItem>
          </i-col>
        </Row>
        <Row style="display:none;">
          <i-col span="24">
            <FormItem>
              <Button type="primary" style="margin-right:20px;" @click="formOk">保存</Button>
              <Button @click="formCancel">取消</Button>
            </FormItem>
          </i-col>
        </Row>
      </Form>
    </Row>
    <!-- 俱乐部成员选择 -->
    <Row style="margin-top:20px;margin-left:10px;" class="titleline">
      <div class="detail-title">俱乐部成员选择</div>
      <div class="line2"></div>
    </Row>
    <Row style="margin-top:20px;margin-left:10px;">
      <i-col span="10">
        <Card style="height:395px;">
          <Form ref="queryForm" :model="queryForm" :rules="queryRoles">
            <Row gutter="30">
              <i-col span="9">
                <FormItem prop="managecome">
                  <Cascader change-on-select :data="organizationList" v-model="queryForm.managecome" @on-change="organizationChange" placeholder="续期专员机构" clearable></Cascader>
                </FormItem>
              </i-col>
              <i-col span="9">
                <FormItem prop="reagentCode">
                  <Input type="text" v-model="queryForm.reagentCode" placeholder="续期专员姓名" clearable/>
                  <!-- <Select v-model="queryForm.reagentCode" placeholder="续期专员姓名" clearable multiple>
                    <Option
                      v-for="item in reagentNameList"
                      :key="item.key"
                      :value="item.key"
                    >{{item.value}}-{{item.key}}</Option>
                  </Select> -->
                </FormItem>
              </i-col>
              <i-col span="6" style="text-align:right;">
                <Button type="primary" @click="selectClubNum">查询</Button>
              </i-col>
            </Row>
          </Form>
          <Table
            ref="selection1"
            :columns="queryColumns"
            :data="companyCodeList"
            height="240"
            @on-selection-change="onSelectChange1"
          ></Table>
          <!-- 俱乐部成员移动 -->
          <Row style="margin-right: -10px;">
            <i-col span="24" style="text-align:right;margin-top:20px">
              <Button type="primary" style="margin-right:10px;" @click="clubTrans1">确定</Button>
            </i-col>
          </Row>
        </Card>
      </i-col>
      <i-col span="2" style="text-align:center;height:395px;line-height:395px;">
        <Icon type="md-swap" style="font-size:60px;" />
      </i-col>
      <i-col span="10">
        <Card style="height:395px;">
          <p slot="title" style="color:rgba(80, 80, 80, 1);font-size:16px;font-weight:bold;">俱乐部成员</p>
          <Table
            ref="selection2"
            :columns="clubColumns"
            :data="clubCodeList"
            @on-selection-change="onSelectChange2"
            height="240"
          ></Table>
          <!-- 俱乐部成员移动 -->
          <Row style="margin-right: -10px;">
            <i-col span="24" style="text-align:right;margin-top:20px">
              <Button type="primary" style="margin-right:10px;" @click="clubTrans2">确定</Button>
            </i-col>
          </Row>
        </Card>
      </i-col>
    </Row>
    <Row style="margin-top:20px;margin-left:10px;">
      <i-col span="24" style="text-align:center">
        <Button type="primary" style="margin-right:20px;" @click="addOk" :loading="loadFlag">保存</Button>
        <Button @click="addCancel">取消</Button>
      </i-col>
    </Row>

    <i-button @click="info" style="display:none"></i-button>
  </Card>
</template>

<script>
export default {
  data() {
    const validateLevel = (rule, value, callback) => {
      if (value) {
        callback();
      } else {
        callback(new Error("俱乐部等级不能为空"));
      }
      callback();
    };
    const validateFile = (rule, value, callback) => {
      if (value.name) {
        callback();
      } else {
        callback(new Error("俱乐部图片不能为空"));
      }
      callback();
    };
    return {
      addForm: {
        clubname: "",
        rewards: [
          {
            value: "",
            index: 1,
            status: 1
          }
        ],
        level: "",
        imgFile: {
          name: ""
        }
      },
      ruleValidate: {
        clubname: [
          { required: true, message: "俱乐部名称不能为空", trigger: "change" }
        ],
        level: [{ validator: validateLevel, trigger: "change" }],
        imgFile: [{ validator: validateFile, trigger: "change" }]
      },
      // 上传图片
      action: "",
      tocken: "",
      deleteFiles: [],
      imgUrl: "",
      /**成员选择变更*/
      queryForm: {
        managecome: "",
        reagentCode: ""
      },
      queryRoles: {
        managecome: [
          { required: true, type:"array", message: "续期机构不能为空", trigger: "change" }
        ]
      },
      organizationList: [],
      reagentNameList: [],
      //表格1
      queryColumns: [
        {
          type: "selection",
          width: 60,
          align: "center"
        },
        {
          title: "续期专员姓名",
          key: "agentname",
          width: 160
        },
        {
          title: "所属机构",
          key: "managecomname",
          width: 140
        },
        {
          title: "员工工号",
          key: "agentcode",
          minWidth: 120
        }
      ],
      companyCodeList: [],
      /**分页*/
      index1: 1, // 当前页码
      pageSize1: 500, // 每页记录数量
      //表2
      clubColumns: [
        {
          type: "selection",
          width: 60,
          align: "center"
        },
        {
          title: "续期专员姓名",
          key: "agentname",
          width: 160
        },
        {
          title: "所属机构",
          key: "managecomname",
          width: 140
        },
        {
          title: "员工工号",
          key: "agentcode",
          minWidth: 120
        }
      ],
      clubCodeList: [],
      /**分页*/
      index2: 1, // 当前页码
      pageSize2: 500, // 每页记录数量
      //加入俱乐部名单
      leftCodeList: [],
      //移除俱乐部名单
      rightCodeList: [],
      submitLoading: false,
      // 俱乐部ID
      clubId: "",
      // 用户信息
      userInfo: [],
      dataObj: null,
      loadFlag: false
    };
  },
  methods: {
    info(tip) {
      this.$Message.info(tip);
    },
    // 获取用户信息
    getUserInfo() {
      this.api.getUserInfo().then(res => {
        this.userInfo = res.data;
      });
    },
    // 续期机构拉框信息
    getProfessionalList() {
      // 续期机构下拉框
      // this.api.selectUerList().then(res => {
      //   this.organizationList = [];
      //   if (res.code == 200 && res.data != null) {
      //     this.organizationList = res.data[0].listKeyValueVOS;
      //   } else {
      //     this.organizationList = [];
      //   }
      // });
      this.api.remanagecomList().then(res => {
        if (res.code == 200 && res.data != null) {
          let arr = []
          arr.push(res.data)
          arr.forEach(one=>{
            one.value = one.comcode
            one.label = one.comcode + '-' + one.name
            one.children = one.chilDren || []
            if (one.children) {
              one.chilDren.forEach(two=>{
                two.value = two.comcode
                two.label = two.comcode + '-' + two.name
                two.children = two.chilDren || []
                if (two.children) {
                  two.children.forEach(three=>{
                    three.value = three.comcode
                    three.label = three.comcode + '-' + three.name
                    three.children = three.chilDren || []
                    if (three.children) {
                      three.children.forEach(four=>{
                        four.value = four.comcode
                        four.label = four.comcode + '-' + four.name
                        four.children = four.chilDren || []
                      })
                    }
                  })
                }
              })
            }
          })
          console.log(arr);
          this.organizationList = arr
        } else {
          this.organizationList = [];
        }
      });
    },
    // 根据管理机构查询员工
    // organizationChange(value) {
    //   //console.log(value);
    //   if (!value) {
    //     this.reagentNameList = [];
    //   } else {
    //     $.ajax("scrm-gateway/scrm-uer/api/List/sekectreangencode/" + value, {
    //       method: "get",
    //       contentType: "application/json;charset=utf-8",
    //       headers: {
    //         Authorization: sessionStorage.getItem("credentials")
    //       },
    //       success: res => {
    //         //console.log(res.data);
    //         if (res.code == 200 && res.data != null) {
    //           this.reagentNameList = res.data;
    //         } else {
    //           this.reagentNameList = [];
    //         }
    //       },
    //       error: res => {
    //         // console.log(res);
    //         this.$Message.info(res.msg);
    //       }
    //     });
    //   }
    // },
    // 查询需要选择的俱乐部成员
    selectClubNum() {
      this.$refs.queryForm.validate(valid => {
        if (valid) {
          let obj = {
            agentname: this.queryForm.reagentCode,
            managecom: this.queryForm.managecome[this.queryForm.managecome.length-1],
            clubid: this.clubId,
            index: 1,
            pageSize: this.pageSize1,
            type: 0
          };
          for (let item in obj) {
            if (obj[item] == null || obj[item].length == 0) {
              delete obj[item];
            }
          }
          this.pageObj1 = obj;
          // console.log(obj)
          this.api.selectClubNum(obj).then(res => {
            if (res.code == 200) {
              if (res.data) {
                this.companyCodeList = res.data.records;
                this.total1 = res.data.total;
              } else {
                this.companyCodeList = [];
                this.total1 = 0;
              }
            } else {
              this.companyCodeList = [];
              this.total1 = 0;
              this.info(res.msg);
            }
          });
        }
      });
    },
    // 新增奖励
    handleAdd() {
      this.addForm.rewards.push({
        value: "",
        index: this.addForm.rewards.length + 1,
        status: 1
      });
    },
    // 删除奖励
    handleRemove(index) {
      this.addForm.rewards.splice(index, 1);
    },
    rateChange(value) {
      this.addForm.level = value;
    },

    /**上传照片*/
    // 上传文件转到手动提交
    handleUpload(file) {
      if (
        file.type == "image/jpeg" ||
        file.type == "image/jpg" ||
        file.type == "image/png"
      ) {
        // 保存需要上传的文件
        let keyID = Math.random()
          .toString()
          .substr(2);
        file["keyID"] = keyID;
        this.addForm.imgFile = file;
        this.imgUrl = window.URL.createObjectURL(file);
        return false;
      } else {
        // 文件格式验证失败
        this.info("上传文件非图片格式，请重新上传！");
      }
    },
    // 删除文件
    delectFile() {
      // 保存到删除文件数组
      this.deleteFiles = this.addForm.imgFile;
      this.addForm.imgFile = {
        name: "",
        status: ""
      };
    },
    // 上传文件
    upload() {
      this.$refs.upload.post(this.addForm.imgFile);
    },
    // 上传成功
    uploadSuccess(response, file, fileList) {
      // console.log(response, file, fileList);
      this.loadFlag = false;
      this.info(file.name + "上传成功");
      this.info("俱乐部新建成功");
      this.$router.push({
        name: 'club'
      });
      return true;
    },
    // 文件上传失败
    uploadFail(response, file, fileList) {
      // console.log(response, file, fileList);
      this.loadFlag = false;
      this.info(file.name + "上传失败");
      this.info("俱乐部新建失败");
      this.addForm.imgFile = [];
      return false;
    },

    // 选择添加成员
    onSelectChange1(selection) {
      this.leftCodeList = selection;
    },
    // 选择移除成员
    onSelectChange2(selection) {
      this.rightCodeList = selection;
    },

    // 添加俱乐部成员
    clubTrans1() {
      if (this.leftCodeList.length > 0) {
        this.leftCodeList.forEach(element => {
          this.clubCodeList.push(element);
          for (let i = 0; i < this.companyCodeList.length; i++) {
            if (this.companyCodeList[i].agentcode == element.agentcode) {
              this.companyCodeList.splice(i, 1);
              return 0;
            }
          }
        });
        this.leftCodeList = [];
      } else {
        this.info("必须选择一个成员!");
      }
      // console.log(this.clubCodeList)
    },

    // 移除俱乐部成员
    clubTrans2() {
      if (this.rightCodeList.length > 0) {
        this.rightCodeList.forEach(element => {
          this.companyCodeList.push(element);
          for (let i = 0; i < this.clubCodeList.length; i++) {
            if (this.clubCodeList[i].agentcode == element.agentcode) {
              this.clubCodeList.splice(i, 1);
              return 0;
            }
          }
        });
        this.rightCodeList = [];
      } else {
        this.info("必须选择一个成员!");
      }
    },

    // 保存
    formOk() {
      this.$refs.addForm.validate(valid => {
        if (valid) {
          if (this.clubCodeList.length > 0) {
            this.loadFlag = true;
            let rewordList = [];
            this.addForm.rewards.forEach(element => {
              rewordList.push(element.value);
            });
            let agentcodeList = [];
            this.clubCodeList.forEach(element => {
              agentcodeList.push(element.agentcode);
            });
            let date = new Date();
            let obj = {
              agentcodeList: agentcodeList + "",
              clubId: this.clubId,
              clubLevel: this.addForm.level,
              clubName: this.addForm.clubname,
              createOperator: this.userInfo.employeeNO,
              managecom: this.userInfo.managecom,
              // multipartFile: this.addForm.imgFile,
              rewardList: rewordList + ""
            };
            // console.log(obj);
            this.$refs.upload.data = obj;
            // 上传文件
            this.upload();
          } else {
            this.info("请选择俱乐部成员！");
          }
        }
      });
    },
    addOk() {
      this.formOk();
    },
    // 取消
    formCancel() {
      this.$refs.addForm.resetFields();
      this.addForm.rewards = [
        {
          value: "",
          index: 1,
          status: 1
        }
      ];
    },
    addCancel() {
      this.loadFlag = false;
      this.formCancel();
      this.addForm.imgFile = {
        name: "",
        status: ""
      };
      //设置选择成员列表为空--
      this.rightCodeList = [];
      this.leftCodeList = [];
      this.clubCodeList = [];
      this.$refs.selection1.selectAll(false);
      this.$refs.selection2.selectAll(false);
    }
  },
  mounted() {
    // this.action = sessionStorage.getItem("userIp") + "api/club/insertUerClub";
    this.action = "/scrm-gateway/scrm-uer/api/club/insertUerClub";
    this.tocken = sessionStorage.getItem("credentials");

    this.getUserInfo();
    this.getProfessionalList();
    // this.selectClubNum();
  },
  created() {
    this.clubId = this.$route.query.clubId;
  }
};
</script>


<style lang="less" scoped>
.ivu-col-span-14{
  flex: 0 0 63.333333%;
  max-width: 63.333333%;
}
.ivu-col-span-3{
  flex: 0 0 25%;
  max-width: 50%;
}
.titleline{
  display: flex;
  flex-direction: column;
}
.ivu-icon-ios-close:before {
  color: #000 !important;
}
.ivu-card-body{
  padding: 16px;
}
.detail-title {
  font-size: 16px;
  font-weight: bold;
  color: rgba(80, 80, 80, 1);
}
.line1 {
  width: 64px;
  height: 3px;
  background-color: rgba(24, 144, 255, 1);
  border-radius: 2px;
  margin-top: 4px;
}
.line2 {
  width: 114px;
  height: 3px;
  background-color: rgba(24, 144, 255, 1);
  border-radius: 2px;
  margin-top: 4px;
}

.form-tip {
  width: 50%;
  height: 32px;
  display: inline-flex;
  align-items: center;
  position: absolute;
  left: 102%;
  top: 0;
  color: rgba(255, 87, 51, 1);
  &-1 {
    width: 30%;
    height: 32px;
    display: inline-flex;
    align-items: center;
    position: absolute;
    left: 102%;
    top: 0;
  }
  &-1 > i {
    color: rgba(24, 144, 255, 1);
    cursor: pointer;
  }
}

.demo-upload-list {
  display: inline-block;
  width: 300px;
  text-align: center;
  height: 188px;
  line-height: 188px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  margin-right: 4px;
}
.demo-upload-list img {
  display: block;
  width: 100%;
  height: 100%;
}
.demo-upload-list-cover {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
}
.demo-upload-list:hover .demo-upload-list-cover {
  display: block;
}
.demo-upload-list-cover i {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}
</style>